package global

import (
	"fmt"
	"time"

	"github.com/olivere/elastic/v7"
)

var es *elastic.Client

type tracelog struct{}

// 实现输出
func (tracelog) Printf(format string, v ...interface{}) {
	fmt.Printf(format, v...)
}

func InitElasticSearch() error {
	fName := "InitElasticSearch"
	err := GetEsEngine(
		Config.GetString("es.protocol"),
		Config.GetString("es.host"),
		Config.GetString("es.port"),
		Config.GetString("es.user"),
		Config.GetString("es.passwd"),
	)

	if err != nil {
		return fmt.Errorf("%s Init fail %s", fName, err.Error())
	}
	fmt.Println("初始ES成功")
	return nil
}

func GetEsEngine(protocol, host, port, user, pass string) (err error) {
	if es != nil {
		return
	}
	es, err = elastic.NewClient(
		// 设置Elastic服务地址
		elastic.SetURL(fmt.Sprintf("%s://%s:%s", protocol, host, port)),
		// 連線帳密
		elastic.SetBasicAuth(user, pass),
		// 是否转换请求地址，默认为true,当等于true时 请求http://ip:port/_nodes/http，将其返回的url作为请求路径
		elastic.SetSniff(false),
		// 心跳检查,间隔时间
		elastic.SetHealthcheckInterval(time.Second*5),
		//调试的时候再开启日志打印,方便跟踪错误
		//elastic.SetInfoLog(new(tracelog)),
		//elastic.SetTraceLog(new(tracelog)), // 这一 必须的
	)
	if err != nil {
		return fmt.Errorf("connect ElasticSearch error %s", err.Error())
	}
	return
}

func GetEs() *elastic.Client {
	return es
}
